package  com.unity3d.player;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;

import com.unity3d.player.UnityPlayer;

import java.io.IOException;


/**
 * Created by chenyong on 2024/4/8.
 */

public class WebViewActivity extends Activity {


    public static final int NONE = 0;

    public static final int PHOTORESOULT = 3;// 结果

    public static final String IMAGE_UNSPECIFIED = "image/*";



    private String LOG_TAG = "LOG_ZDQ";
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        Intent intent = new Intent(Intent.ACTION_PICK, null);

        //intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
        intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);

        startActivityForResult(intent, PHOTORESOULT);
        Log.d(LOG_TAG, "打开相册！");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(LOG_TAG, "resultCode ：" + resultCode);
        if (resultCode == NONE)
            return;

        if (data == null)
            return;

        // 外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
        ContentResolver resolver = getContentResolver();
        Bitmap bm=null;
        // 获得图片的uri
        Uri originalUri = data.getData();
        try {
            bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
        } catch (IOException e) {
            e.printStackTrace();
        }


        String[] proj = {MediaStore.Images.Media.DATA};

        // 好像是android多媒体数据库的封装接口，具体的看Android文档
        // Cursor cursor = managedQuery(originalUri, proj, null, null, null);
        Cursor cursor= getContentResolver().query(originalUri,proj,null,null,null);
        // 按我个人理解 这个是获得用户选择的图片的索引值
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        // 将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToFirst();
        Log.e(LOG_TAG, "索引 _path:" + column_index);
        // 最后根据索引值获取图片路径
        String _path = cursor.getString(column_index);

        UnityPlayer.UnitySendMessage("Main Camera", "GetPhoto", _path);
         Log.d(LOG_TAG, "UnitySendMessage _path:" + _path);
        super.onActivityResult(requestCode, resultCode, data);

        //读取完，关闭当前Activity
        this.finish();
    }
}

